//
//  FourViewController.m
//  BGM
//
//  Created by liuqin on 2018/11/25.
//  Copyright © 2018年 com.alirtc.demo. All rights reserved.
//

#import "ContactViewController.h"
#import "Common.h"
#import "ContactTableViewCell.h"
#import "ContaceNewViewController.h"

#import "MessageCommonTableViewCell.h"
#import "FriendViewController.h"
#import "BGMUser.h"
#import "BGMHTTP.h"
#import "BGMuserFriendClass.h"
#import "ContactDataHelper.h"
#import "CommonView.h"
#import "SVProgressHUD.h"
#import "ChatViewController.h"
#import <NIMSDK/NIMSDK.h>
@interface ContactViewController ()
<
UITableViewDelegate,UITableViewDataSource,
ContactTableViewCellDelegate,
NIMSystemNotificationManagerDelegate>

@property (nonatomic, strong)UITableView *userTable;

@property (nonatomic, strong)NSArray *sectionArray;  //通讯录
@property (nonatomic, strong)NSArray *rowArray; //通讯录

@property (nonatomic, strong)NSMutableArray *appArray;


@property (nonatomic, strong)NSMutableArray *iphonInvitArray;

@property (nonatomic, assign)BOOL isFresh;

@end

@implementation ContactViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if(self.isForward){
        self.backBtn.hidden = NO;
    }
}
#pragma mark app同意添加好友
- (void)freshContactView{
    [self.appArray removeAllObjects];
    self.sectionArray = @[];
    self.rowArray = @[];
    [self getBGMFriends];
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navview.hidden = NO;
    self.titleLabel.hidden = NO;
    self.titleLabel.text = @"联系人";
    
    if(self.isForward){
        self.backBtn.hidden = NO;
    }
    
    self.iphonInvitArray = [[NSMutableArray alloc]init];
    
    
    //app添加好友
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(freshContactView) name:@"freshContactView" object:nil];
    //app启动时通迅录更新
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(freshContactViewController) name:@"freshContactViewController" object:nil];
    
//
    
    [self getBGMFriends];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UILabel *line = [[UILabel alloc]initWithFrame:CGRectMake(0, self.tabBarController.tabBar.frame.origin.y-0.5, SCREENW, 0.5)];
    line.backgroundColor = [UIColor grayColor];
    line.alpha = 0.3;
    [self.view addSubview:line];
    
    self.appArray = [[NSMutableArray alloc]init];
    
    
//    UIView *searchView = [[UIView alloc]initWithFrame:CGRectMake(15, self.navview.frame.origin.y+self.navview.frame.size.height+10, SCREENW-30, 40)];
//    searchView.backgroundColor = [UIColor clearColor];
//    searchView.layer.masksToBounds = YES;
//    searchView.layer.cornerRadius = 20;
//    searchView.layer.borderColor = bgmgrayColor.CGColor;
//    searchView.layer.borderWidth = 0.3;
//    [self.view addSubview:searchView];
//    float y = searchView.frame.origin.y+searchView.frame.size.height;
    self.userTable = [[UITableView alloc]initWithFrame:CGRectMake(0, self.navview.frame.size.height, SCREENW, SCREENH-(SCREENH>736?90:50)-self.navview.frame.size.height)];
    self.userTable.delegate = self;
    self.userTable.dataSource = self;
    self.userTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.userTable];
    
    [[NIMSDK sharedSDK].systemNotificationManager addDelegate:self];
  
}
#pragma mark 启动应用执行
-(void)freshContactViewController{
    [self.appArray removeAllObjects];
    [self.iphonInvitArray removeAllObjects];
    self.isFresh = YES;
    [self getBGMFriends];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1+1+self.sectionArray.count;
 
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section ==0) {
        return 1;
    }else if (section==1){
        NSLog(@" --%d",(int)self.appArray.count);
        return self.appArray.count;
    }else{
        NSArray *array = [self.rowArray objectAtIndex:section-2];
        return array.count;
    }
 }
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==2) {
        return 45;
    }
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section ==0) {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREENW, 45)];
        return label;
    }else if(section ==1){
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREENW, 45)];
        return label;
    }else{
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREENW, 45)];
        label.text = [NSString stringWithFormat:@"  %@",[self.sectionArray objectAtIndex:section-2]];
        label.textColor = bgmgrayColor;
        label.font = [UIFont systemFontOfSize:13];
        return label;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return indexPath.section == 0 ? 61 : 52;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
 
    if (indexPath.section ==0) {
        static NSString *identifier = @"MessageCommonTableViewCell";
        MessageCommonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[MessageCommonTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [cell.iconimageView setImage:[UIImage imageNamed:@"right_1"]];
        cell.messageLabel.text = @"新的朋友";
        return cell;
    }
    else
    {
        static NSString *identifier = @"ContactTableViewCell";
        ContactTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[ContactTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.contactDelegate = self;
        }
        if (indexPath.section ==1) {
             BGMuserFriendClass *friend =[self.appArray objectAtIndex:indexPath.row];
            [cell setFriendValue:friend isInvit:@"" row:indexPath];
        }else{
            
            if(self.rowArray.count>0){
                NSArray *array = [self.rowArray objectAtIndex:indexPath.section -2];
                BGMuserFriendClass *friend = [array objectAtIndex:indexPath.row];
                if (self.iphonInvitArray.count>0) {
                    NSArray *array1 = [self.iphonInvitArray objectAtIndex:indexPath.section -2];
                    NSString *str = [array1 objectAtIndex:indexPath.row];
                      [cell setFriendValue:friend isInvit:str row:indexPath];
                }
            }

        }
        return cell;
    }
}
//右边
- (NSArray *)sectionIndexTitlesForTableView:(UITableView* )tableView{
    return self.sectionArray;
}
//- (NSInteger)tableView:(UITableView*)tableView sectionForSectionIndexTitle:(NSString*)title atIndex:(NSInteger)index
//
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
 
    if(indexPath.section ==0){
        ContaceNewViewController *vc = [[ContaceNewViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if(indexPath.section ==1){
        if(self.appArray.count ==0){
            return;
        }
        
        BGMuserFriendClass *friend = [self.appArray objectAtIndex:indexPath.row];
        if (self.isForward) {
                ChatViewController *vc = [[ChatViewController alloc]init];
                vc.otherName = friend.name;
                vc.OtherId = friend.spareTwo;
                vc.otherImage = friend.headImage;
                vc.messageInfo = self.messageDic;
                vc.isforewoard = YES;
                vc.isforewoardforHome = self.isForwardFormHome;
                //自定义消息有用到
                vc.messageId = self.messageId;
                vc.connectionUserId = self.connectionUserId;
                vc.helpUsersId = self.helpUsersId;
                NIMSession *session = [NIMSession session:friend.spareTwo type:NIMSessionTypeP2P];
                vc.historysession = session;
                [self.navigationController pushViewController:vc animated:YES];
        }
        else{
                FriendViewController *vc = [[FriendViewController alloc]init];
                vc.userId = [BGMUser shareInstance].userId;
                vc.userToken = [BGMUser shareInstance].userToken;
                vc.chUsersId = friend.spareTwo;
                vc.otherImage = friend.headImage;
                vc.ftype = UserFriend;
                vc.otherName = friend.name;
                [self.navigationController pushViewController:vc animated:YES];
        }
    
    }
    else{
        
    }
   
}

- (void)getBGMFriends{
    if (self.isFresh) {
        
    }else{
        [SVProgressHUD showWithStatus:@"正在更新联系人信息"];

    }
    NSDictionary *params = @{@"userToken":[BGMUser shareInstance].userToken,@"userId":[BGMUser shareInstance].userId};
    [BGMHTTP requestWithMethodName:@"contacts/getContactsList" parameters:params completion:^(BOOL success, NSError *error, NSDictionary *result) {
        NSString *code = [NSString stringWithFormat:@"%@",[result objectForKey:@"code"]];
        if([code isEqualToString:@"200"]){
            if(self.isForward){
                [SVProgressHUD dismiss];
            }else{
                if (self.isFresh) {
                    [SVProgressHUD dismiss];
                }else{
                    [SVProgressHUD showSuccessWithStatus:@"获取通讯录成功~"];
                }
            }
            NSArray *array = [result objectForKey:@"data"];
            [self reloadTableView:array];
            self.isFresh = NO;
        }else{
            [SVProgressHUD showErrorWithStatus:@"更新联系人信息出错"];
        }
    }];
}

- (void)reloadTableView:(NSArray *)array{
    NSMutableArray *resultArray = [[NSMutableArray alloc]init];
    NSMutableArray *resultAPP = [[NSMutableArray alloc]init];
    [self.appArray removeAllObjects];

    for (NSDictionary *dic in array) {
        BGMuserFriendClass *friend = [[BGMuserFriendClass alloc]init];
        friend.creatTime = [NSString stringWithFormat:@"%@",[dic objectForKey:@"creatTime"]];
        friend.headImage = [NSString stringWithFormat:@"%@",[dic objectForKey:@"headImage"]];
        friend.friendId = [NSString stringWithFormat:@"%@",[dic objectForKey:@"id"]]; //唯一
        friend.name = [NSString stringWithFormat:@"%@",[dic objectForKey:@"name"]];
        friend.spareOne = [NSString stringWithFormat:@"%@",[dic objectForKey:@"spareOne"]];
        friend.spareTwo = [NSString stringWithFormat:@"%@",[dic objectForKey:@"spareTwo"]];
        friend.type = [NSString stringWithFormat:@"%@",[dic objectForKey:@"type"]];
        friend.userId = [NSString stringWithFormat:@"%@",[dic objectForKey:@"userId"]];
        friend.isInvite = @"0";
        if([dic objectForKey:@"sendsmsTime"]){
            friend.sendsmsTime = [NSString stringWithFormat:@"%@",[dic objectForKey:@"sendsmsTime"]];
        }else{
            friend.sendsmsTime = @"";
        }
        
        if([friend.type isEqualToString:@"1"]){
            [self.appArray addObject:friend];
            [resultAPP addObject:dic];
        }else{
            [resultArray addObject:friend];
        }
    }
    self.rowArray=[ContactDataHelper getFriendListDataBy:resultArray];
    self.sectionArray=[ContactDataHelper getFriendListSectionBy:[self.rowArray mutableCopy]];
    [self.userTable reloadData];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:resultAPP forKey:@"appFriend"];
    [userDefaults synchronize];

    
    for (NSArray *array in self.rowArray) {
        NSMutableArray *newArray = [[NSMutableArray alloc]init];
        for (BGMuserFriendClass *user in array) {
            NSString *time = user.sendsmsTime;
            if (time.length==0) {
                [newArray addObject:@"0"];
            }else{
                int sever = [time intValue];
                int current = [[self getNowTimeTimestamp]intValue];
                if (current-sever>=604800000) {
                    [newArray addObject:@"0"];
                }else{
                   [newArray addObject:@"1"];
                }
            }
        }
        [self.iphonInvitArray addObject:newArray];
    }
}


- (NSString *)getNowTimeTimestamp{
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSString*timeString = [NSString stringWithFormat:@"%0.f", a];//转为字符型
    return timeString;
}


- (void)clickBack{
    if (self.isForward) {
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }
    
 }


-(void)clickOtherFriend:(NSString *)iphone indexPath:(NSIndexPath *)index{
   
    NSDictionary *param = @{@"userToken":[BGMUser shareInstance].userToken,@"userId":[BGMUser shareInstance].userId,@"phoneNum":iphone};
    
    [BGMHTTP requestWithMethodName:@"contacts/joinAppSendMesssage" parameters:param completion:^(BOOL success, NSError *error, NSDictionary *result) {
        NSLog(@"");
        NSString *code = [NSString stringWithFormat:@"%@",[result objectForKey:@"code"]];
        if ([code isEqualToString:@"200"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSMutableArray *array = [self.iphonInvitArray objectAtIndex:index.section-2];
                [array replaceObjectAtIndex:index.row withObject:@"1"];
                [self.iphonInvitArray replaceObjectAtIndex:index.section-2 withObject:array];
                NSIndexPath *indexPath=index;
                [self.userTable reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
            });
        }
        
        
    }];
}



@end
